document.getElementById('app').style.display = 'block'
var mySwiper
let baseUrl = 'https://api.77du.net/ciff/miniappapi' //环境一

$(function () {
  //移除所有输入框
  $('.pgc-img-caption-ipt').remove()
  getVideo()
  initAllSwiper()
  setTimeout(()=>{
    clearHtmlP()
  })
})


function initAllSwiper(){
  let contain=document.getElementsByClassName('cus-swiper')
  for (let index = 0; index < contain.length; index++) {
    const element =contain[index]
    initSwiper(index)
  }

  //溢出所有的p标签
  for (let index = 0; index < $('.contain_article > p').length; index++) {
    const element = $('.contain_article > p')[index];
    if(element.outerHTML==="<p><br></p>"){
      element.remove()
      console.log(element)
    }
  }
}


//初始化轮播图
function initSwiper(index) {
  let contain=document.getElementsByClassName('cus-swiper')
  let swiper = $(`<div class="swiper-container" id='swiper${index}'></div>`)
  let hasImg=[]
  let imgbox=document.getElementsByClassName('cus-swiper')[index]
  if(imgbox){
    hasImg=imgbox.getElementsByTagName('img')
  }else{
    hasImg=[]
  }
  console.log(hasImg,swiper)
  let str = '<div class="swiper-wrapper">'
  if(hasImg.length==0)return
  $.each(hasImg, (index, v) => {
    str += `<div class="swiper-slide"><img src="${v.src}"/></div>`
  })
  swiper.append(str + '</div')
  console.log(swiper)

  $(contain[index]).html(swiper)
  let swiperLength = hasImg.length
  new Swiper(`#swiper${index}`, {
    autoplay: 5000, //可选选项，自动滑动
    loop: true,
    pagination: {
      el: '.swiper-pagination',
      clickable: true,
    },
    onInit(swiper) {
      let swiperIndexEle = $(
        `<div class='swiperElement selectIndex${index}'><span>${
          1 + '/' + swiperLength
        }</span></div>`
      )
      $(`#swiper${index}`).append(swiperIndexEle)
    },
    onTouchEnd:(swiper)=>{
      let indexw=index
      setTimeout(()=>{
        let index=swiper.realIndex+1
        let str = `<span>${index}/${swiperLength}</span>`
        $(`.selectIndex${indexw}`).html(str)
        console.log(index)
      },100)
    },
    // onSlideChangeEnd(swiper) {
    //   //当前的索引
    //   let index = (swiper.activeIndex-1+3)%(3);
      
      
    // },
  })
}
//清除
function clearHtmlP(){
  for (let index = 0; index < $('.contain_article > p').length; index++) {
    const element = $('.contain_article > p')[index];
    if(element.outerHTML==="<p><br></p>"){
      element.remove()
      console.log(element)
    }
  }
}
//获取视频地址
function getVideo() {
  let videobox = $('.player-wrap') || null
  let videodiv = $('.player-wrap > div')
  if (videobox) {
    //是否有插入视频盒子
    let vid = videodiv.attr('videorid')
    if (!vid) return
    let videotag = $('<video controls="controls"></video>')
    console.log(vid)
    $.ajax({
      url: baseUrl + '/vod/video/play/url?videoId=' + vid,
      type: 'get',
      success: (res) => {
        console.log(res)
        // if(res.data.code=='000000'){
        videotag.attr('src', res.data.fileUrl)
        videotag.attr('poster', res.data.mainImage)
        videobox.html(videotag)
        // }
      },
    })
  }
}
function getQueryString(name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  var r = window.location.search.substr(1).match(reg)
  if (r != null) return decodeURI(r[2])
  return null
}

let axios2 = axios.create({
  headers: { token: getQueryString('token'), r: new Date().getTime() },
})
let vm = new Vue({
  el: '#app',
  data() {
    return {
      token: getQueryString('token'), //用户token
      list: [],
      text: '', //用户修改的数据
      really: false, //真正的输入框的谈起
      replay: '', //标志用户是回复，还是评论信息
      listSwitch: false, //评论列表
      imgOrText: true,
      havere: true,
      text: '',
      id: getQueryString('id') || '979252467743064064',
      start: '',
      static: 'https://static.77du.net/template/ciff/news',
      like: [
        `https://static.77du.net/template/ciff/news/img/aixin_k.png`,
        `https://static.77du.net/template/ciff/news/img/dzaixin.png`,
      ], //点赞的图片
      likeIndex: 0, //点赞图片的索引
      showLIkeGif: false, //动态点赞的图片
      discussList: [], //所有的评论数据
      hasChart: true,
      index: 0,
      size: 10,
      allData: {},
      openItem: '', //选择某个用户的评论
      hold: '',
      toast: false,
      toasttitle: '',
      scrollTop: 0,
    }
  },
  directives: {
    focus: {
      // 指令的定义
      bind: function (el) {
        el.addEventListener('click', function () {
          setTimeout(() => {
            document.getElementById('reallyInput').focus()
            console.log('聚焦')
          }, 20)
        })
      },
    },
  },
  computed: {
    previewList() {
      // 文章中部的聊天的三条数据
      if (this.discussList.length > 0) {
        let s = this.discussList.length > 3 ? 3 : this.discussList.length
        let arr = []
        for (let index = 0; index < s; index++) {
          arr.push(this.discussList[index])
        }
        return arr
      } else {
        return 0
      }
    },
  },
  watch: {
    listSwitch: function (newvalue) {
      document.body.style.overflow = newvalue == true ? 'hidden' : 'auto'
    },
    really: function (newvalue) {
      if (newvalue == true) {
        this.scrollTop = $(document).scrollTop()
        this.$nextTick(() => {
          setTimeout(() => {
            this.$refs.reallyInput.focus()
          }, 100)
        })
      } else {
        this.$nextTick(() => {
          let isiOS = !!navigator.userAgent.match(
            /\(i[^;]+;( U;)? CPU.+Mac OS X/
          )
          if (!isiOS) return
          // $('html,body').animate(
          //   {
          //     scrollTop: this.scrollTop,
          //   },
          //   200
          // )
          this.scrollTop = 0
        })
      }
    },
  },
  methods: {
    goback() {
      wx.miniProgram.navigateBack()
    },
    startinput() {
      this.start = true
    },
    send() {
      this.really = false
    },
    onScroll(e) {
      // console.log(e)
      if (
        e.srcElement.scrollTop + e.srcElement.offsetHeight >=
        e.srcElement.scrollHeight
      ) {
        if (this.hasChart == true) {
          console.log('加载数据')
          this.getcomData()
        }
      }
    },
    openList() {
      this.listSwitch = true
    },
    async likeArtice() {
      if (!this.token) {
        this.showToast('未登录')
        setTimeout(() => {
          // wx.miniProgram.switchTab({
          //   url:"/pages/my/my"
          // })
          wx.miniProgram.redirectTo({
            url: "/pages/login/login?type=0&id=" + this.id,
          });
        }, 1500)
        return
      }
      try {
        //点赞心
        if (this.likeIndex == 0) {
          this.showLIkeGif = true
          this.allData.favorite.favoriteNumber=Number(this.allData.favorite.favoriteNumber)+1
          setTimeout(() => {
            this.showLIkeGif = false
          }, 2125)
          let res = await this.likeArt()
          if (res.data.code == '000000') {
          }
        } else {
          if (!Number(this.allData.favorite.favoriteNumber) == 0) {
            this.allData.favorite.favoriteNumber=Number(this.allData.favorite.favoriteNumber)-1
          }
          let res = await this.delectLike()
          if (res.data.code == '000000') {
          }
        }
      } catch (error) {}
      this.likeIndex == 0 ? (this.likeIndex = 1) : (this.likeIndex = 0)
    },
    //获取推荐的数据
    getrecommend() {
      axios({
        url: baseUrl + '/news/like?subjectId=' + this.id,
        method: 'get',
      }).then((res) => {
        console.log(res)
        if (res.data.code === '000000') {
          this.list = res.data.list
        }
      })
    },
    jump(item) {
      let url = ''
      if (item.type == 2) {
        //文章
        window.location.href = `https://api.77du.net/ciff/miniappapi/news/${item.id}.html?id=${item.id}&token=${this.token}`
        return
      } else if (item.type == 3) {
        //图集
        url = '/pages/photo/photo?id=' + item.id
      } else if (item.type == 5) {
        //视频
        url = '/pages/video/video?id=' + item.id
      } else if (item.type == 7) {
        //专题
        url = '/pages/picAtlas/picAtlas'
      } else if (item.type == 6) {
        //排行榜
        url = '/pages/crunchies/crunchies'
      } else if (item.type == 1) {
        return
      }
      wx.miniProgram.navigateTo({
        url,
      })
    },
    async getcomData(first = false) {
      this.index++
      let res = await this.getCommentlistData(this.index, this.size, this.id)
      console.log(res)
      if (res.data.code === '000000') {
        const { content } = res.data.data
        console.log(content)
        if (content != null && content != [] && content.length > 0) {
          this.discussList.push(...(content || []))
        } else {
          this.hasChart = false
        }
      }
    },
    getCommentlistData(index, size, subjectId) {
      return new Promise((resolve, reject) => {
        axios({
          url: baseUrl + '/subject/comment',
          headers: { token: this.token, r: new Date().getTime() },
          method: 'get',
          params: {
            index: index,
            size: size,
            subjectId: subjectId,
          },
        })
          .then((res) => {
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    async submite() {
      this.start=false
      if (!this.token) {
        this.showToast('未登录')
        setTimeout(() => {
          // wx.miniProgram.switchTab({
          //   url:"/pages/my/my"
          // })
          console.log('跳转')
          wx.miniProgram.redirectTo({
            url: "/pages/login/login?type=0&id=" + this.id,
          });
        }, 1500)
        return
      }
      
      if (this.openItem == '') {
        let res = await this.userTalk(this.id, this.text)
        console.log(res)
        if (res.code == '000000') {
          this.showToast('评论成功,等待审核', 2000)
        } else {
          this.showToast('评论失败', 2000)
        }
        this.refresh()
      } else {
        let res = await this.replayMsg(this.openItem.id, this.text)
        if (res.code == '000000') {
          this.showToast('回复成功,等待审核', 2000)
        } else {
          this.showToast('回复失败', 2000)
        }
        this.refresh()
      }
    },
    showToast(title, time = 1500) {
      this.toast = true
      this.toasttitle = title
      setTimeout(() => {
        this.toast = false
      }, time)
    },
    //属性数据
    refresh(isfresh = true) {
      this.really = false
      this.text = ''
      this.discussList = []
      this.index = 0
      this.openItem = ''
      this.hold = ''
      if (isfresh == true) {
        this.getcomData()
      }
    },
    closeModel() {
      this.really = false
      this.text = ''
      this.hold = ''
      this.openItem = ''
      this.start = false
    },
    focusin() {
      this.$nextTick(() => {
        setTimeout(() => {
          this.$refs.reallyInput.focus()
        }, 100)
      })
    },
    //评论
    userTalk(id, text) {
      return new Promise((reslove, reject) => {
        $.ajax({
          url: baseUrl + '/subject/comment',
          type: 'post',
          headers: {
            token: getQueryString('token'),
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            r: new Date().getTime(),
          },
          data: {
            resourceId: id,
            intro: text,
          },
          success: (res) => {
            reslove(res)
          },
        })
      })
    },
    //收藏文章
    likeArt() {
      return new Promise((reslove, reject) => {
        $.ajax({
          url: baseUrl + '/subject/favorite?subjectId=' + this.id,
          type: 'post',
          headers: {
            token: getQueryString('token'),
            r: new Date().getTime(),
          },
          success: (res) => {
            reslove(res)
          },
        })
      })
    },
    //取消收藏
    delectLike() {
      return new Promise((resolve, reject) => {
        $.ajax({
          url: baseUrl + '/subject/favorite?subjectIds=' + this.id,
          type: 'DELETE',
          headers: {
            token: getQueryString('token'),
            r: new Date().getTime(),
          },
        }).then((res) => {
          resolve(res)
        })
      })
    },
    replayPerson(item) {
      this.openItem = item
      this.really = true
      console.log(item)
      this.focusin()
    },
    //说点什么打开输入框
    openReallyInput() {
      this.really = true
      this.replay=''
    },
    //打开某个评论
    replayPersonSecond(item) {
      this.openItem = item
      this.really = true
      this.start = true
      this.replay = '回复' + item.userName
      this.focusin()
      console.log('回复内容')
    },
    //回复消息请求
    replayMsg(atCommentId, intro) {
      return new Promise((resolve, reject) => {
        $.ajax({
          url: baseUrl + '/subject/comment/reply',
          type: 'post',
          headers: {
            token: getQueryString('token'),
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            r: new Date().getTime(),
          },
          data: {
            atCommentId,
            intro,
          },
        }).then((res) => {
          resolve(res)
        })
      })
    },
    //真正输入框的真实高度和恢复高度
    recordHieght() {
      '聚焦触发'
      // this.$nextTick(() => {
      //   this.scrollTop = $(document).scrollTop()
      //   console.log($(document).scrollTop())
      // })
    },
    recoverHieght() {
      // let isiOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
      // if (!isiOS) return
      // $('html,body').animate(
      //   {
      //     scrollTop: this.scrollTop,
      //   },
      //   200
      // )
      // this.scrollTop = 0
    },
    clearState(){
      this.really=true
      this.openItem=''
      this.replay=''
    },
    //跳转到回复列表
    jumpReplayPage(item){
      wx.miniProgram.navigateTo({
        url:'/pages/discuss/discuss?id='+item.id
      })
    }
  },
  mounted() {
    this.getrecommend()
    this.getcomData()
    axios2({
      url: baseUrl + '/news/' + this.id,
      method: 'get',
    }).then((res) => {
      if (res.data.code === '000000') {
        this.allData = res.data.data
        this.allData.favorite.isFavorite == true
          ? (this.likeIndex = 1)
          : (this.likeIndex = 0) //是否收藏过
      }
    })
  },
})
